var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];



//运营经理关联
function myFunction(){
    //销售经理

    var manager=$("#organization_name").val();
    var user_data = {
        "pageNum":1,

        "pageSize":20,

    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if(data.errorCode=="0"){
            var jsonObj =data.group;
            if(jsonObj==""){
                $("#tuan").html("<li>无数据</li> ");
            }else {
                console.log(jsonObj)

                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    optionstring += "<li onclick='relation("+ jsonObj[i].id+",\""+jsonObj[i].organization_name+"\")' data-align=\"" + jsonObj[i].id + "\" > " + jsonObj[i].organization_name + "</li>";
                }
                $("#tuan").html(optionstring);
                console.log(jsonObj)
            }
        }else{
            $("#tuan").html("<li>无数据</li> ");
        }
    }
    /*root.member.getGroup*/
    web.doAjax(root.member.getGroup,'post',user_data, succCallBack);

}
//取光标
$("#organization_name").focus(function () {
    $("#tuan").show()
});
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tuan").length == 0 && $(e.target).closest("#organization_name").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tuan").hide()
    }
})
function relation(id,ce) {
    $("#organization_name").val(ce).text(id)
    $("#tuan").hide()
    console.log($("#organization_name").text())
}
//初始化所属分公司列表
ascription()
function ascription() {
    var user_data = {
    }
    var succCallBack = function (data, status, response) {
        //console.log(data)
        if(data.errorCode=="0") {
            var dataInter=data.group;
            var interText = doT.template($("#ascription_bob").text());
            $("#ascription_lsit").html(interText(dataInter));
        }
    };
    return web.doAjax(root.inter.getGroup, 'post', user_data, succCallBack);
}


searchList();
function searchList() {
    var ascriptionlsit=""
    if($("#ascription_lsit option:selected").text()=='请选择所属分公司' ||$("#ascription_lsit option:selected").text()=='空'){
        ascriptionlsit=""
    }else {
        ascriptionlsit=$("#ascription_lsit option:selected").text()
    }
console.log($("#ascription_lsit option:selected").text())
    let per ="";
    if($("#ascription_lsit option:selected").text()=='请选择所属分公司' ||$("#ascription_lsit option:selected").text()=='') {
     per = {"pageNum":1,
        "pageSize":50,

        "name":$("#name").val(),
        "mobile": $("#mobile").val(),
        "inviteCode": $("#inviteCode").val(),
        "beginTime":$("#beginTime").val(),
        "endTime":$("#endTime").val(),
        "status":$("#status").val()
    };


    }else {
        per = {"pageNum":1,
            "pageSize":50,

            "name":$("#name").val(),
            "mobile": $("#mobile").val(),
            "inviteCode": $("#inviteCode").val(),
            "beginTime":$("#beginTime").val(),
            "endTime":$("#endTime").val(),
            "status":$("#status").val()
        };
        let key = "companyName";
        let value = ascriptionlsit;

        eval("per." + key + "='" + value + "'");
    }
console.log(per)

    $.ajax({
        url: root.member.groundPushPersonList,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify(per),
        success: function (data) {
            console.log(data);
            console.log(data.errorCode)
            if(data.errorCode==0){
                $("#modal-delete").modal("hide");
            }else {
                $("#modal-delete").modal("inline");
            }
            // couponlist(data.result);
            list(data.list, 0);
            $('.M-box3').pagination({
                pageCount: data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    console.log(api)
                    let per1 ="";
                    if($("#ascription_lsit option:selected").text()=='请选择所属分公司' ||$("#ascription_lsit option:selected").text()=='') {
                        per1 = {"pageNum":api.getCurrent(),
                            "pageSize":50,

                            "name":$("#name").val(),
                            "mobile": $("#mobile").val(),
                            "inviteCode": $("#inviteCode").val(),
                            "beginTime":$("#beginTime").val(),
                            "endTime":$("#endTime").val(),
                            "status":$("#status").val()
                        };


                    }else {
                        per1 = {"pageNum":api.getCurrent(),
                            "pageSize":50,

                            "name":$("#name").val(),
                            "mobile": $("#mobile").val(),
                            "inviteCode": $("#inviteCode").val(),
                            "beginTime":$("#beginTime").val(),
                            "endTime":$("#endTime").val(),
                            "status":$("#status").val()
                        };
                        let key = "companyName";
                        let value = ascriptionlsit;

                        eval("per1." + key + "='" + value + "'");
                    }
                    $.ajax({
                        /*root.member.custAccountList*/
                        url: root.member.groundPushPersonList,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify(per1),
                        success: function (result) {
                            console.log(result)
                            list(result.list);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}


function list(data, index){

    sessionStorage.setItem("groundPushPersonList", JSON.stringify(data));
    dataSource.splice(0,dataSource.length);//清空数组

    if(data !=null && data != ''){
        var datashu =data[0].rowNo;


    $.each(data, function (i, field) {
        var rowData = new Array();
        var datashus = datashu++

        rowData.push(field.rowNo);

        rowData.push(field.name);
        rowData.push(field.mobile);
        rowData.push(field.companyName);//所属分公司
        rowData.push(field.inviteCode);
        rowData.push("<img style=\"width:73px;hight:67px;\"   src='"+field.sweepCode+"'>");

        rowData.push(field.createTime);
        rowData.push(field.status);

        rowData.push(datashus);
        rowData.push(field.sweepCode );
        rowData.push(field.inviteCode);
        rowData.push(field.companyId);
        dataSource.push(rowData);
    });
    }else{

    }
    initDataTable(dataSource);

    function initDataTable(dataSource) {

        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },


                {
                    "render": function (data, type, row, meta) {
                        var val = row[8]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = ""
                        if (row[7] == 10) {
                            val = row[1]
                        }else if(row[7]==20){
                            val = ''+row[1]+'(关闭)'
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val=""
                        if(row[3]==''){
                            val = '<span>'+'空'+'</span>';

                        }else {
                            val = '<span>'+row[3]+'</span>';

                        }
                        return val;
                    },
                    "targets":3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[5]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 5
                },
                //列表日期格式
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        var date = row[6];
                        var split = date.split(" ");
                        val = split[0] + '<br/>' + split[1];
                        return val;
                    },
                    "targets":6
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[7]==10){
                            val='开启'
                        }
                        else if(row[7]==20){
                            val='关闭'
                        }
                        return val;
                    },
                    "targets":7
                },

                {
                    "render": function (data, type, row, meta) {
                        var val='';
                        if(row[7]==10){
                            val = '<div class="action" id="action'+row[4]+'">' +
                                '<a class="powerButton 177" style="margin-right: 20px">' +
                                '<span class="list" id="1'+row[4]+'" onclick="confirm(1'+row[4]+')">关闭</span>' +
                                '</a>'+
                                '<a class="powerButton 179">' +
                                '<span class="list "  ' +

                                'onclick="download(\''+row[9]+'\',\''+row[4]+'\' )">下载二维码' +
                                '</span>' +
                                '</a>' +
                                '&nbsp;&nbsp;&nbsp;&nbsp;<a class="powerButton 178"  onclick="updataaa(\''+row[10]+'\',\''+ row[3]+'\',\''+ row[1]+'\',\''+ row[11]+'\')">修改</a>'+
                                '</div>';


                        }
                        else if(row[7]==20){
                            val = '<div class="action" ' +
                                'id="action'+row[4]+'">' +
                                '<a class="powerButton 177" style="margin-right: 20px">' +
                                '<span class="list" id="1'+row[4]+'" ' +
                                'onclick="confirm2(1'+row[4]+')">开启</span></a>'+
                                '<a class="powerButton 179"><span class="list"  ' +
                                'onclick="download(\''+row[9]+'\',\''+row[4]+'\' )">下载二维码' +

                                '</span>' +
                                '</a>' +
                                '&nbsp;&nbsp;&nbsp;&nbsp;<a  class="powerButton 178"   onclick="updataaa(\''+row[10]+'\',\''+ row[3]+'\',\''+ row[1]+'\',\''+ row[11]+'\')">修改</a>'+
                                '</div>';




                        }
                        return val;
                    },
                    "targets":8
                }


            ]
        });
//权限控制函数
        power()
    };
}

//修改
function updataaa(inviteCode,invitename,name,companyId) {
    $("#modifyInformation").modal("show");
    $("#names").val(name)
    $("#inviteCodes").val(inviteCode)
    //分公司显示
    discouncfftdata()
    function discouncfftdata() {
        //解码
        var company="";
        var companyIds=""
        if(invitename==''){
            company="空"
            companyIds="0"
        }else {
            company=invitename
            companyIds=companyId
        }
        //初始化 省
        var user_data = {
        }
        var succCallBack = function (data, status, response) {
            if(data.errorCode == 0){
                var tab_data=data.group;
                var cer = '';
                if(tab_data == ''){
                    cer = '<option value=""></option>'
                    $("#geta").html(cer);
                }else{

                    cer = '<option value='+companyIds+' disabled="disabled" selected>'+company+'</option><option value="">空</option>'
                    for(var i=0; i<tab_data.length; i++){
                        cer += '<option value="'+tab_data[i].id+'">'+tab_data[i].organization_name+'</option>'
                    }
                    $("#geta").html(cer);
                }
            }
        };
        web.doAjax(root.inter.getGroup, 'post', user_data, succCallBack);

    }
}
//取消
function closemodify() {
    $("#modifyInformation").modal("hide");
}
//确定
function modifyadd() {
    if( $("#names").val()==""){
        $.Huimodalalert('请填写姓名！',2000);
        return false;
    }
    var companName="";
    var companyId="";
    if($("#geta option:selected").text()=='空'){
        companName="";
        companyId="0";
    }else {
        companName=$("#geta option:selected").text();
        companyId=$("#geta option:selected").val()
    }
    $.ajax({
        contentType: "application/json;charset=UTF-8",
        url:root.member.updatePushmanInfo,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify({
            "inviteCode":$("#inviteCodes").val(),
            "name":$("#names").val(),
            "companyId":companyId,
            "companyName":companName,
            "operateUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,

        }),
        success: function (data) {
           if(data.errorCode==0){
               $.Huimodalalert('编辑成功',2000);
               $("#modifyInformation").modal("hide");
               searchList()
           }else{
               $.Huimodalalert(data.msg,2000);
           }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })


}

function format(date,str){
    var mat={};
    mat.M=date.getMonth()+1;//月份记得加1
    mat.H=date.getHours();
    mat.s=date.getSeconds();
    mat.m=date.getMinutes();
    mat.Y=date.getFullYear();
    mat.D=date.getDate();
    mat.d=date.getDay();//星期几
    mat.d=check(mat.d);
    mat.H=check(mat.H);
    mat.M=check(mat.M);
    mat.D=check(mat.D);
    mat.s=check(mat.s);
    mat.m=check(mat.m);
    console.log(typeof mat.D)
    if(str.indexOf(":")>-1){
        mat.Y=mat.Y.toString().substr(2,2);
        return mat.Y+"/"+mat.M+"/"+mat.D+" "+mat.H+":"+mat.m+":"+mat.s;
    }
    if(str.indexOf("/")>-1){
        return mat.Y+"/"+mat.M+"/"+mat.D+" "+mat.H+"/"+mat.m+"/"+mat.s;
    }
    if(str.indexOf("-")>-1){
        return mat.Y+"-"+mat.M+"-"+mat.D+" "+mat.H+"-"+mat.m+"-"+mat.s;
    }
}
//关闭弹框
var index=0;
function confirm(id,val) {
    var curInd = layer.confirm('<span id="status" style="width:200px;height:100px;resize: none;" maxlength="200" >您确定要关闭此账号吗？</span>', {title:'提示',btn: ['确定', '取消']}, function(index){
         //alert("id:"+id+"00,curInd"+curInd);
        finish1(id,curInd,val);
        layer.close(curInd);
    },function(){
        layer.close(curInd);

    });
}
//第一个
function finish1(id,val){
    var target = document.getElementById(''+id+'');
    //alert("target2:"+target);
    target.parentElement.parentElement.parentElement.previousElementSibling.innerHTML='关闭';
    console.log(target)
    //alert("target:"+target);
    //var reason=$('#reason'+id+'').val();
    //console.log(reason)
    if(id!=''){
        var idstr=id+"";
        id=(idstr).substring(1);
        //alert("id777:"+id);
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            /*root.member.updateMemberStatus*/
            url:root.member.updateGroundPushPerson,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            data: JSON.stringify({
                "inviteCode":id,
                "status":20,//关闭
                optUserId:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                optUserName:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name

            }),
            success: function (data) {
                console.log(data);
                //alert("333");
                target.onclick = null;
                target.setAttribute("onclick", 'confirm('+id+')')
                target.parentElement.parentElement.parentElement.previousElementSibling.innerHTML='关闭'
                searchList();

            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }
    else{
        $.Huimodalalert('处理结果不能为空！',2000);
    };
    layer.close(index);
}

//开启弹框
var index=0;
function confirm2(id,val) {
    var curInd = layer.confirm('<span id="status" style="width:200px;height:100px;resize: none;" maxlength="200" >您确定要开启此账号吗？</span>', {title:'提示',btn: ['确定', '取消']}, function(index){
        //alert("id:"+id);
        finish2(id,curInd,val)
        layer.close(curInd);
    },function(){
        layer.close(curInd);

    });
}
//更新下载
function updateDownNum(inviteCode){
    if(null!=inviteCode&&''!=inviteCode){
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            /*root.member.updateMemberStatus*/
            url:root.member.updateGroundDownloadNum,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            data: JSON.stringify({
                "inviteCode":inviteCode,
                "isDownloadOpt":"10"//点击下载操作
            }),
            success: function (data) {

            },
            error: function () {

            }
        })}
    else{

    };

}
//第一个
function finish2(id,val){
    var target = document.getElementById(''+id+'');

    target.parentElement.parentElement.parentElement.previousElementSibling.innerHTML='开启';
    //alert("target:"+target);
    var reason=$('#reason'+id+'').val();
    if(reason!=''){
        var idstr=id+"";
        id=(idstr).substring(1);
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            /*root.member.updateMemberStatus*/
            url:root.member.updateGroundPushPerson,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            data: JSON.stringify({
                "inviteCode":id,
                "status":10,//开启
                optUserId:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                optUserName:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name

            }),
            success: function (data) {

                target.onclick = null;
                target.setAttribute("onclick", 'confirm('+id+')')
                searchList();
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        })}
    else{
        $.Huimodalalert('处理结果不能为空！',2000);
    };
    layer.close(index);
}

//查看详情
function detail(title,url,member_id) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url +'?member_id='+member_id
    });
    layer.full(index);
}

//查看详情
function download(urlStr,fileName) {
    var indexValue=urlStr.indexOf("?Expires");
    urlStr=urlStr.substr(0,indexValue);
    var url=encodeURIComponent(urlStr);
    var url=root.xunjiadan.downLoadFromUrl + '?urlStr=' +url+'&fileName=' + fileName;
    window.location.href=url;
    //updateDownNum(fileName);//fileName文件名为邀请码值
}
function upLoadFile() {
    $("#fileUp").trigger('click');
}
//下载模版
function downLoadFile(){
    var url=root.member.downloadImportTemplate;
    window.location.href=url;
}
//关闭弹框
function closeSure(){

    /*$("#tip").html("");*/
    $("#modal-delete").modal("hide");
    setTimeout(location.replace(location.href),3000)
    /*searchList();*/
    /*location.replace(location.href);*/
}

//地推导入
function putDataToPage() {

    /*渲染spu sku值到页面*/
    var formData = new FormData();
    formData.append('file', $("#fileUp")[0].files[0]);

    $.ajax({
        url: root.member.groundPushImport,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            if (data.errorCode == 0) {
                $("#tip").html(data.errorMessage);
                $("#modal-delete").modal("show");

            } else {
                $("#tip").html(data.errorMessage);
                $("#modal-delete").modal("show");
                /**固定弹框
                layer.confirm(data.errorMessage, {
                    btn: ['确定'] //按钮
                }, function(){
                    window.location.href=location.href;
                });**/
            }
        }
    });
}



//限制字符
var len
var Preser
var common=10//要限制输入的字数
function checkMaxIut(me) {
    var text=$(me).val()
    strlen(text)
    if(len>common){
        $(me).val(Preser)
    }else {
        Preser=$(me).val()
    }
}
function strlen(str){
    len = 0;
    for (var i=0; i<str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
            len++;
        } else {
            len+=2;
        }
    }
    return len;
}